package com.example.interfaces.controller;

import com.example.application.service.AuthService;
import com.example.infrastructure.annotation.Idempotent;
import com.example.infrastructure.annotation.OperationLog;
import com.example.infrastructure.common.Result;
import com.example.infrastructure.security.JwtUtils;
import com.example.interfaces.dto.LoginRequest;
import com.example.interfaces.dto.LoginResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户认证相关接口")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    @OperationLog(module = "认证管理", type = "登录", description = "用户登录")
    @Idempotent(expireTime = 5, message = "登录操作太频繁，请5秒后再试")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            LoginResponse response;
            if ("password".equals(request.getLoginMethod())) {
                response = authService.loginByPassword(request);
            } else if ("sms".equals(request.getLoginMethod())) {
                response = authService.loginBySms(request);
            } else {
                return Result.error("不支持的登录方式");
            }
            return Result.success(response);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 发送短信验证码
     */
    @PostMapping("/sms/send")
    @Operation(summary = "发送短信验证码")
    public Result<String> sendSmsCode(@Parameter(description = "手机号") @RequestParam String phone) {
        try {
            authService.sendSmsCode(phone);
            return Result.success("验证码发送成功");
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出")
    @OperationLog(module = "认证管理", type = "登出", description = "用户登出", recordResult = false)
    public Result<String> logout(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (StringUtils.hasText(token)) {
                authService.logout(token);
            }
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新token")
    public Result<LoginResponse> refreshToken(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (!StringUtils.hasText(token)) {
                return Result.error("token不能为空");
            }
            LoginResponse response = authService.refreshToken(token);
            return Result.success(response);
        } catch (Exception e) {
            log.error("刷新token失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}